/**
 * 
 */
package com.foxconn.ipebg.common.base.security;

import java.util.List;

import ipebg.mzk.facade.entity.MsAdminUser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Component;
 
@Component("securityUserHolder")
public class SecurityUserHolder {

	@Autowired
	private SessionRegistry sessionRegistry;
	/**
	 * Returns the current user
	 * 
	 * @return
	 */
	public static MsAdminUser  getCurrentUser() {

		MsAdminUser user =null;
		try{
			Object obj=SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			if(obj!=null&&!obj.toString().equalsIgnoreCase("anonymousUser")){
				user= (MsAdminUser)obj; 
			}			
		}catch(Exception e){
			e.printStackTrace();			
		}
		return user;
	}

	public static boolean authenticateUser(MsAdminUser userWraper,HttpServletRequest request){
		try{
			Authentication authentication = new UsernamePasswordAuthenticationToken(userWraper, userWraper.getPassword(), userWraper.getAuthorities());
			authentication.setAuthenticated(true);
			SecurityContextHolder.getContext().setAuthentication(authentication);
			HttpSession session = request.getSession(true);
			session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());
			return true;
		}catch(Exception e){
			
			return false;
		}		
	}
	
	
	public List<Object> getLoginUsers(){
		List<Object> slist =sessionRegistry.getAllPrincipals();
		return slist;
	}
}
